package com.jeecg.guangdian.controller;
import com.jeecg.guangdian.entity.BusinessUserMapEntity;
import com.jeecg.guangdian.service.BusinessUserMapServiceI;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import java.io.OutputStream;
import org.jeecgframework.core.util.BrowserUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.core.util.ResourceUtil;
import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.Map;
import java.util.HashMap;


/**   
 * @Title: Controller  
 * @Description: 选择用户列表
 * @author onlineGenerator
 * @date 2019-07-25 23:07:21
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/businessUserMapController")
public class BusinessUserMapController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(BusinessUserMapController.class);

	@Autowired
	private BusinessUserMapServiceI businessUserMapService;
	@Autowired
	private SystemService systemService;
	


	/**
	 * 选择用户列表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		String orgCode = String.valueOf(request.getParameter("orgCode"));
		String orgType = String.valueOf(request.getParameter("orgType"));
		request.setAttribute("orgCode",orgCode);
		request.setAttribute("orgType",orgType);
		return new ModelAndView("com/jeecg/guangdian/businessUserMapList");
	}

	@RequestMapping(params = "datagrid")
	public void datagrid(BusinessUserMapEntity businessUserMap,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(BusinessUserMapEntity.class, dataGrid);
		//查询条件组装器
		TSUser user = ResourceUtil.getSessionUser();
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, businessUserMap, request.getParameterMap());
		Map<String,String> deptMap = new HashMap<>();
		this.orgCq(cq,request,deptMap);
		//cq.eq("createBy",user.getUserName());
		cq.addOrder("userName",SortDirection.asc);
		cq.add();
		this.businessUserMapService.getDataGridReturn(cq, true);
		List<BusinessUserMapEntity> businessUserMapEntities = dataGrid.getResults();
		for(int i=0;i<businessUserMapEntities.size();i++){
			businessUserMapEntities.get(i).setSysOrgCode(deptMap.get(businessUserMapEntities.get(i).getSysOrgCode()));
			businessUserMapEntities.get(i).setSysCompanyCode(deptMap.get(businessUserMapEntities.get(i).getSysCompanyCode()));
		}
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除选择用户列表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(BusinessUserMapEntity businessUserMap, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		businessUserMap = systemService.getEntity(BusinessUserMapEntity.class, businessUserMap.getId());
		message = "选择用户列表删除成功";
		try{
			businessUserMapService.delete(businessUserMap);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "选择用户列表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除选择用户列表
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "选择用户列表删除成功";
		try{
			for(String id:ids.split(",")){
				BusinessUserMapEntity businessUserMap = systemService.getEntity(BusinessUserMapEntity.class, 
				id
				);
				businessUserMapService.delete(businessUserMap);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "选择用户列表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加选择用户列表
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(BusinessUserMapEntity businessUserMap, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "领用人添加成功";
		try{
			String checkUser = "select count(1) from business_user_map t where t.sys_company_code = '"+businessUserMap.getSysCompanyCode()+"' and t.sys_org_code = '"+businessUserMap.getSysOrgCode()+"' and t.user_card = '"+businessUserMap.getUserCard()+"'";
			if(businessUserMapService.getCountForJdbc(checkUser)>0){
				message = "领用人身份证号在此栏目已存在";
				j.setMsg(message);
				return j;
			}
			businessUserMapService.save(businessUserMap);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "领用人添加失败";
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新选择用户列表
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(BusinessUserMapEntity businessUserMap, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "选择用户列表更新成功";
		BusinessUserMapEntity t = businessUserMapService.get(BusinessUserMapEntity.class, businessUserMap.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(businessUserMap, t);
			businessUserMapService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "选择用户列表更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 选择用户列表新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(BusinessUserMapEntity businessUserMap, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(businessUserMap.getId())) {
			businessUserMap = businessUserMapService.getEntity(BusinessUserMapEntity.class, businessUserMap.getId());
			req.setAttribute("businessUserMapPage", businessUserMap);
		}
		return new ModelAndView("com/jeecg/guangdian/businessUserMap-add");
	}
	/**
	 * 选择用户列表编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(BusinessUserMapEntity businessUserMap, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(businessUserMap.getId())) {
			businessUserMap = businessUserMapService.getEntity(BusinessUserMapEntity.class, businessUserMap.getId());
			req.setAttribute("businessUserMapPage", businessUserMap);
		}
		return new ModelAndView("com/jeecg/guangdian/businessUserMap-update");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","businessUserMapController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(BusinessUserMapEntity businessUserMap,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(BusinessUserMapEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, businessUserMap, request.getParameterMap());
		List<BusinessUserMapEntity> businessUserMaps = this.businessUserMapService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"选择用户列表");
		modelMap.put(NormalExcelConstants.CLASS,BusinessUserMapEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("选择用户列表列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,businessUserMaps);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(BusinessUserMapEntity businessUserMap,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"选择用户列表");
    	modelMap.put(NormalExcelConstants.CLASS,BusinessUserMapEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("选择用户列表列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<BusinessUserMapEntity> listBusinessUserMapEntitys = ExcelImportUtil.importExcel(file.getInputStream(),BusinessUserMapEntity.class,params);
				for (BusinessUserMapEntity businessUserMap : listBusinessUserMapEntitys) {
					businessUserMapService.save(businessUserMap);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(e.getMessage());
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	/**
	 * 获取部门
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "getUserList")
	@ResponseBody
	public AjaxJson getUserList(HttpServletRequest req) {
		AjaxJson j = new AjaxJson();
		try {
			TSUser user = ResourceUtil.getSessionUser();
			CriteriaQuery cq = new CriteriaQuery(BusinessUserMapEntity.class);
			Map<String,String> deptMap = new HashMap<>();
			this.comOrg(cq,req,deptMap);
			cq.addOrder("userName",SortDirection.asc);
			cq.add();
			List<BusinessUserMapEntity> users =  this.systemService.getListByCriteriaQuery(cq, false);
			//将List转换成JSON存储
			JSONArray userList = new JSONArray();
			if(users!=null && users.size()>0){
				for(int i=0;i<users.size();i++){
					JSONObject jsonParts = new JSONObject();
					jsonParts.put("userName", users.get(i).getUserName());
					jsonParts.put("sysCompanyCode", users.get(i).getSysCompanyCode());
					jsonParts.put("costAddr", users.get(i).getCostAddr());
					jsonParts.put("sysOrgCode",users.get(i).getSysOrgCode());
					jsonParts.put("userCard",users.get(i).getUserCard());
					userList.add(jsonParts);
				}
			}
			Map<String,Object> attrs = new HashMap<String, Object>();
			attrs.put("user", userList);
			j.setAttributes(attrs);
		} catch (Exception e) {
			j.setSuccess(false);
			e.printStackTrace();
		}
		return j;
	}
	@RequestMapping(params = "getUserListdatagrid")
	public void getUserListdatagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(BusinessUserMapEntity.class, dataGrid);
		//查询条件组装器
		TSUser user = ResourceUtil.getSessionUser();
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, request.getParameterMap());
		Map<String,String> deptMap = new HashMap<>();
		this.orgCq(cq,request,deptMap);
		cq.addOrder("userName",SortDirection.asc);
		dataGrid.setRows(1000);
		cq.add();
		this.businessUserMapService.getDataGridReturn(cq, true);
		List<BusinessUserMapEntity> businessUserMapEntities = dataGrid.getResults();
		for(int i=0;i<businessUserMapEntities.size();i++){
			businessUserMapEntities.get(i).setOrgCode(deptMap.get(businessUserMapEntities.get(i).getSysOrgCode()));
			businessUserMapEntities.get(i).setCompanyCode(deptMap.get(businessUserMapEntities.get(i).getSysCompanyCode()));
			businessUserMapEntities.get(i).setId(businessUserMapEntities.get(i).getSysOrgCode()
			+","+businessUserMapEntities.get(i).getSysCompanyCode()
					+","+businessUserMapEntities.get(i).getUserCard()
					+","+businessUserMapEntities.get(i).getCostAddr()
					+","+businessUserMapEntities.get(i).getUserName());

		}
		TagUtil.datagrid(response, dataGrid);
	}

	private void comOrg(CriteriaQuery cq,HttpServletRequest request,Map<String,String> deptMap){
		//查询条件组装器
		TSUser user = ResourceUtil.getSessionUser();
		String userId =user.getId();
		CriteriaQuery depteq = new CriteriaQuery(TSDepart.class);
		String queryDept = "select org_id from t_s_user_org where user_id=:userid";
		List<String> deptIds = systemService.getSession().createSQLQuery(queryDept).setString("userid",userId).list();
		if(deptIds!=null && deptIds.size()>0){
			Object values[] = deptIds.toArray();
			depteq.in("id", values);
		}else{
			depteq.eq("id","-1" );
		}
		List<String> deptCodes = new ArrayList<>();
		List<String> companyCodes = new ArrayList<>();
		depteq.add();
		List<TSDepart> departList =  this.systemService.getListByCriteriaQuery(depteq, false);
		for(TSDepart ts:departList){
			if("0".equals(ts.getOrgType())){
				deptCodes.add(ts.getOrgCode());
			}else if("1".equals(ts.getOrgType())){
				companyCodes.add(ts.getOrgCode());
			}
			if(null!=deptMap){
				deptMap.put(ts.getOrgCode(),ts.getDepartname());
			}
		}
		if(CollectionUtils.isEmpty(deptCodes)&&CollectionUtils.isEmpty(companyCodes)){
			cq.eq("sysOrgCode", "-1");
		}
		if(!CollectionUtils.isEmpty(deptCodes)){
			Object values[] = deptCodes.toArray();
			cq.in("sysOrgCode", values);
		}
		if(!CollectionUtils.isEmpty(companyCodes)){
			Object values[] = companyCodes.toArray();
			cq.in("sysCompanyCode", values);
		}
	}
	private void orgCq(CriteriaQuery cq,HttpServletRequest request,Map<String,String> deptMap){
		String orgCode = String.valueOf(null==request.getParameter("orgCode")?"":request.getParameter("orgCode"));
		String orgType = String.valueOf(null==request.getParameter("orgType")?"":request.getParameter("orgType"));
		if("0".equals(orgType)){
			cq.eq("sysOrgCode",orgCode);
		}else if("1".equals(orgType)){
			cq.eq("sysCompanyCode",orgCode);
		}
		//查询条件组装器
		TSUser user = ResourceUtil.getSessionUser();
		String userId =user.getId();
		CriteriaQuery depteq = new CriteriaQuery(TSDepart.class);
		String queryDept = "select org_id from t_s_user_org where user_id=:userid";
		List<String> deptIds = systemService.getSession().createSQLQuery(queryDept).setString("userid",userId).list();
		if(deptIds!=null && deptIds.size()>0){
			Object values[] = deptIds.toArray();
			depteq.in("id", values);
		}else{
			depteq.eq("id","-1" );
		}
		List<String> deptCodes = new ArrayList<>();
		List<String> companyCodes = new ArrayList<>();
		depteq.add();
		List<TSDepart> departList =  this.systemService.getListByCriteriaQuery(depteq, false);
		for(TSDepart ts:departList){
			if("0".equals(ts.getOrgType())){
				deptCodes.add(ts.getOrgCode());
			}else if("1".equals(ts.getOrgType())){
				companyCodes.add(ts.getOrgCode());
			}
			if(null!=deptMap){
				deptMap.put(ts.getOrgCode(),ts.getDepartname());
			}
		}
		if(CollectionUtils.isEmpty(deptCodes)&&CollectionUtils.isEmpty(companyCodes)){
			cq.eq("sysOrgCode", "-1");
		}
		if(!CollectionUtils.isEmpty(deptCodes)){
			Object values[] = deptCodes.toArray();
			cq.in("sysOrgCode", values);
		}
		if(!CollectionUtils.isEmpty(companyCodes)){
			Object values[] = companyCodes.toArray();
			cq.in("sysCompanyCode", values);
		}
	}
}
